import { QueryClient, useQuery } from 'react-query';
import { dehydrate } from 'react-query/hydration'
import { useRouter } from "next/router";
import CourseLayout from "@/components/course-layout";
import Article from "@/components/article";
import { getCourseById, getIntroductionByCourseId } from "@/apis/course";
import { isCourseManager } from '@/tools/data-helpers';

export default function CourseHomePage() {
    const { courseId } = useRouter().query;

    const { data: course } = useQuery(['course', courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getCourseById(courseId)
    });

    const { data: introduction } = useQuery(['introduction', courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getIntroductionByCourseId(courseId)
    });

    return (
        <CourseLayout course={course} courseId={courseId}>
            <Article content={introduction && introduction.content} isCourseManager={isCourseManager(course && course.manager)} courseId={courseId} id={introduction && introduction.id} isIntroduction={true} />
        </CourseLayout>
    );
}

export async function getServerSideProps({ query }) {
    const queryClient = new QueryClient()

    await queryClient.prefetchQuery(['course', query.courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getCourseById(courseId);
    });
    await queryClient.prefetchQuery(['introduction', query.courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getIntroductionByCourseId(courseId);
    });

    return {
        props: {
            dehydratedState: dehydrate(queryClient),
        },
    }
}
